﻿package com.scn.base.util;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;


/**
 * IpTool.java
 * 
 *处理IP相关运算
 *
 * @version 1.0
 * @author 何正军 hzj.400@qq.com
 * 
 *     没有的IP返回南京市区号 
		南京市区号 
		areaMap.put("025", "001001");
		 苏州市区号 
		areaMap.put("0512", "001002");
		 徐州市区号 
		areaMap.put("0516", "001003");
		 无锡市区号 
		areaMap.put("0510", "001004");
		 常州市区号 
		areaMap.put("0510", "001005");
		 南通市区号 
		areaMap.put("0513", "001006");
		 连云港市区号 
		areaMap.put("0518", "001007");
		 淮安市区号 
		areaMap.put("0517", "001008");
		 盐城市区号 
		areaMap.put("0515", "001009");
		 扬州市区号 
		areaMap.put("0514", "001010");
		 镇江市区号 
		areaMap.put("0511", "001011");
		 泰州市区号 
		areaMap.put("0523", "001012");
		 宿迁市区号 
		areaMap.put("0527", "001013");
 * 
 */

public class IpTool {
	
	/**
	 * 全局变量存放缓存的IP数据
	 */
	public static Map<String,String> map = new HashMap<String,String>() ;
	
	/**
	 * 区号对应的地市
	 */
    public static Map<String, String> AREA_MAP =new HashMap<String, String>();
    
    /*
     * 区号地市
     */
    public static Map<String, String> AREA_CODE_NAME = new HashMap<String, String>();
    /*
     * 区号地市
     */
    public static Map<String, String> AREA_NAME = new HashMap<String, String>();
    
    static{
        AREA_MAP.put("025", "nanjing");
        AREA_MAP.put("0512", "suzhou");
        AREA_MAP.put("0516", "xuzhou");
        AREA_MAP.put("0510", "wuxi");
        AREA_MAP.put("0519", "changzhou");
        AREA_MAP.put("0513", "nantong");
        AREA_MAP.put("0518", "lianyungang");
        AREA_MAP.put("0517", "huaian");
        AREA_MAP.put("0515", "yancheng");
        AREA_MAP.put("0514", "yangzhou");
        AREA_MAP.put("0511", "zhenjiang");
        AREA_MAP.put("0523", "taizhou");
        AREA_MAP.put("0527", "suqian");
    }
    
    static{
        AREA_CODE_NAME.put("025", "南京");
        AREA_CODE_NAME.put("0512", "苏州");
        AREA_CODE_NAME.put("0516", "徐州");
        AREA_CODE_NAME.put("0510", "无锡");
        AREA_CODE_NAME.put("0519", "常州");
        AREA_CODE_NAME.put("0513", "南通");
        AREA_CODE_NAME.put("0518", "连云港");
        AREA_CODE_NAME.put("0517", "淮安");
        AREA_CODE_NAME.put("0515", "盐城");
        AREA_CODE_NAME.put("0514", "扬州");
        AREA_CODE_NAME.put("0511", "镇江");
        AREA_CODE_NAME.put("0523", "泰州");
        AREA_CODE_NAME.put("0527", "宿迁");
    }
  
    	static{
        	AREA_NAME.put("nanjing", "南京");
        	AREA_NAME.put("suzhou", "苏州");
        	AREA_NAME.put("xuzhou", "徐州");
        	AREA_NAME.put("wuxi", "无锡");
        	AREA_NAME.put("changzhou", "常州");
        	AREA_NAME.put("nantong", "南通");
        	AREA_NAME.put("lianyungang", "连云港");
        	AREA_NAME.put("huaian", "淮安");
        	AREA_NAME.put("yancheng", "盐城");
        	AREA_NAME.put("yangzhou", "扬州");
        	AREA_NAME.put("zhenjiang", "镇江");
        	AREA_NAME.put("taizhou", "泰州");
        	AREA_NAME.put("suqian", "宿迁");
       
    }
	/**
	 * @param args
	 */
	public static void main(String[] args) throws IOException{

		addStaticIp("F://qqwry//IP.txt") ;
		String as = compareIp("158.208.130.122",map) ;
		System.out.println("区号为   "+as) ;
		
	}
	
	/**
	 * 取得IP，并放进MAP中去，以便于缓存
	 * @param dir 
	 * @param fileName
	 */
	public static void addStaticIp(String fileName ) throws IOException
	{
		if(fileName == null )
		{
			return ;
		}
		FileInputStream fin = null ;
		try {
			fin = new FileInputStream(fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		Reader in = new InputStreamReader(fin);
		BufferedReader bin = new BufferedReader(in);
		String ipNews ="" ;

			while ((ipNews = bin.readLine( )) != null ) {
				String ap[] = ipNews.replaceAll(" ", "-").split("-") ;
				int index =1 ;
				String key = "" ;
				String value = "" ;
				for(int i=0 ;i<ap.length;i++)
				{
					
					if(index<=3&&ap[i]!=null && !ap[i].trim().equals(" ")&&!ap[i].trim().equals("")
							&& ap[i].trim().indexOf(" ")<0  )
					{
						if(index == 1)
						{
							key = replaceIp(ap[i]) ;
						}else if(index ==2 )
						{
							key =key+"-"+ replaceIp(ap[i]) ;
						}else{
							if(ap[i].indexOf("苏州")>=0)
							{
								value= "0512" ;
							}else  	if(ap[i].indexOf("徐州")>=0)
							{
								value= "0516" ;
							} else  if(ap[i].indexOf("无锡")>=0)
							{
								value= "0510" ;
							}else  if(ap[i].indexOf("常州")>=0)
							{
								value= "0519" ;
							}else if(ap[i].indexOf("南通")>=0)
							{
								value= "0513" ;
							}else if(ap[i].indexOf("连云港")>=0)
							{
								value= "0518" ;
							}else if(ap[i].indexOf("淮安")>=0)
							{
								value= "0517" ;
							}else if(ap[i].indexOf("盐城")>=0)
							{
								value= "0515" ;
							}else if(ap[i].indexOf("扬州")>=0)
							{
								value= "0514" ;
							}else if(ap[i].indexOf("镇江")>=0)
							{
								value= "0511" ;
							}else if(ap[i].indexOf("泰州")>=0)
							{
								value= "0523" ;
							}else if(ap[i].indexOf("宿迁")>=0)
							{
								value= "0527" ;
							}else{
								value= "025" ;//南京
							}
						}
						index++ ;
					}
				}
					map.put(key, value) ;
				
			}

		
		
		
	}
	
	/**
	 * 把IP从XXX.XXX.XX.XXX，换成数字如201123122122
	 * @param oldIp
	 * @return
	 */
	private  static String replaceIp(String oldIp)
	{
		if(oldIp == null)
		{
			return null ;
		}
	    String ipArray[] = oldIp.replace(".", "-").split("-") ;
		int ipLength = ipArray.length ;
		String newIp="" ;
		for(int ipA = 0 ;ipA<ipLength;ipA++)
		{
			if(ipA != 0)
			{
				if(ipArray[ipA].length() != 3)
				{
					if(ipArray[ipA].length()==2)
					{
						ipArray[ipA] ="0"+ipArray[ipA] ;
					}else{
						ipArray[ipA] ="00"+ipArray[ipA] ;
					}
				}
			}
			newIp = newIp +ipArray[ipA] ;

		}
		return newIp ;
	}
	
	/**
	 * 如果IP在给范围内，就返回IP对应地方；否则就返南京
	 * @param ip
	 * @param map
	 * @return
	 */
	public  static String compareIp(String ip,Map<String,String> map)
	{
		String area = null;//"025" ;
		long myIp = Long.valueOf(replaceIp(ip)) ;
		Set entries = map.entrySet( );
		if(entries != null) 
		{
			Iterator iterator = entries.iterator( );
		while(iterator.hasNext( )) 
		{
			Map.Entry entry =(Entry) iterator.next( );
		String key = (String)entry.getKey( );
		String keyArray[] = key.split("-") ;
		if(keyArray.length == 2)
		{
			if(myIp>=Long.valueOf(keyArray[0]) &&myIp<=Long.valueOf(keyArray[1]) )
			{
				 area = (String)entry.getValue();
				 return area ;
			}
		}

		  }
		}
		return area ;
	}
	
//	public static String getRemoteAddr(HttpServletRequest request){
//	    String ip = request.getHeader("x-forwarded-for");
//	    if(ip !=null && ip.trim().length()>0 && !ip.equalsIgnoreCase("unknown")){
//	        ip = ip.split(",")[0];
//	    }
//	    else{
//	        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
//	            ip = request.getHeader("Proxy-Client-IP");   
//	        }   
//	        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
//	            ip = request.getHeader("WL-Proxy-Client-IP");   
//	        }   
//	        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {   
//	            ip = request.getRemoteAddr();   
//	        }   
//	    }
//        return ip;  
//	}
	
}
